package org.cyb.demo.controller;

import org.apache.commons.io.FileUtils;
import org.cyb.demo.domain.Course;
import org.cyb.demo.domain.Ppt;
import org.cyb.demo.service.PptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.File;

@Controller
@RequestMapping("/ppt")
public class PptController {

    @Autowired
    private PptService pptService;

    //下载PPT
    @RequestMapping("/pptDownload")
    public ResponseEntity<byte[]> pptDownload(
            Ppt ppt,
            Course course,
            HttpSession httpSession
    ) throws Exception{
        //根据name查询ppt
        Ppt target = pptService.findOneByName(ppt);
        String fileName = target.getPptName();
        String path = httpSession.getServletContext().getRealPath("/upload/ppt/");
        path = path + File.separator + course.getCourseName();
        //获取要下载文件的File对象
        File file = new File(path + File.separator + fileName);
        // 创建springframework的HttpHeaders对象
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开PPT
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
